package com.dev.op.service.impl;
import com.dev.op.VO.JudgeResultVO;
import com.dev.op.VO.JudgeTestCaseVO;
import com.dev.op.config.JudgeProperties;
import com.dev.op.entity.JudgeRequest;
import com.dev.op.entity.LanguageConfig;
import com.dev.op.enums.ResultCode;
import com.dev.op.enums.TestCaseResultCode;
import com.dev.op.exceptions.BizException;
import com.dev.op.service.JudgeService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Autowired
    private JudgeProperties judgeProperties;

    /**
     * 负责将judge core传回的 结果进行 解析，打包，后续不关心
     * @param request
     * @return JudgeResultVO: 返回从 FastAPI读取的内容
     * @throws Exception
     */
    @Override
    public JudgeResultVO judge(JudgeRequest request) throws Exception {
        //准备请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //构造 HttpEntity
        HttpEntity<JudgeRequest> entity = new HttpEntity<>(request, headers);
        //发起请求
        RestTemplate restTemplate = new RestTemplate();
        //需改进
        String url = "";
        if(request.isRunBatch()){
            url = "http://localhost:8081/judge/group";
        }
        else{
            url = "http://localhost:8081/judge";
        }
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    String.class
            );
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(response.getBody(), JudgeResultVO.class);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new BizException(ResultCode.JUDGE_SERVER_DOWN);
        }
    }
}
